using UnityEngine;
using QFramework;
using ProjectSurvivor;
using Unity.VisualScripting;

// 1.请在菜单 编辑器扩展/Namespace Settings 里设置命名空间
// 2.命名空间更改后，生成代码之后，需要把逻辑代码文件（非 Designer）的命名空间手动更改
namespace QFramework.Example
{
	public partial class Player : ViewController
	{
		public float MovementSpeed = 5;//玩家速度
		public static Player Default;//单例
		private void Awake()
		{
			Default = this;
		}
		/// <summary>
		/// 对象或组件销毁之前执行清理操作
		/// </summary>
		private void OnDestroy()
		{
			Default = null;
		}
		void Start()
		{
			//碰撞
			HurtBox.OnTriggerEnter2DEvent(collider2D =>
			{
				var hitBox = collider2D.GetComponent<HitBox>();
				if (hitBox)
				{
					//敌人
					if (hitBox.Owner.CompareTag("Enemy"))
					{
						Global.HP.Value--;
						if (Global.HP.Value <= 0)
						{
							AudioKit.PlaySound("Die");
							//"优雅销毁" (DestroyGameObjGracefully) 是指在销毁 GameObject 时
							// 确保进行必要的清理工作、停止协程、释放资源、执行动画等，确保没有任何未处理的状态或资源，避免出现内存泄漏或逻辑错误。
							this.DestroyGameObjGracefully();
							//打开结束面板
							UIKit.OpenPanel<UIGameOverPanel>();
						}
						else
						{
							AudioKit.PlaySound("Hurt");
						}
					}
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			void UpdateHp()
			{
				HPValue.fillAmount = Global.HP.Value / (float)Global.MaxHp.Value;
			}
			Global.HP.RegisterWithInitValue(hp =>
			{
				UpdateHp();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
			Global.MaxHp.RegisterWithInitValue(hp =>
			{
				UpdateHp();
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		void Update()
		{
			//移动
			var horizontal = Input.GetAxisRaw("Horizontal");
			var vertical = Input.GetAxisRaw("Vertical");
			//方向
			var targetVelocity = new Vector2(horizontal, vertical).normalized * MovementSpeed;
			//刚体速度=方向*速度;
			SelfRigidbody2D.velocity = Vector2.Lerp(SelfRigidbody2D.velocity, targetVelocity, 1 - Mathf.Exp(-Time.deltaTime * 5));
		}


	}


}
